package com.example.mall.service.impl;

import com.example.mall.doc.ProductsDoc;
import com.example.mall.mapper.HighlightResultMapper;
import com.example.mall.query.ProductsQueryDto;
import com.example.mall.repository.ProductsRepository;
import com.example.mall.result.AggrPageList;
import com.example.mall.result.AggrTermsBucket;
import com.example.mall.result.PageList;
import com.example.mall.service.IESProductService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xxxliu
 * @CreateTime: 2025-05-20
 * @Version: 1.0
 */
@Service
public class ESProductServiceImpl implements IESProductService {
    @Autowired
    private ProductsRepository repository;

    @Autowired
    private ElasticsearchRestTemplate template;

    @Autowired
    private HighlightResultMapper highlightResultMapper;

    @Override
    public void save(ProductsDoc doc) {
        repository.save(doc);
    }

    @Override
    public void saveAll(ProductsDoc[] docs) {
        // 将数组转换为 List
        java.util.List<ProductsDoc> productList = Arrays.asList(docs);
        // 调用 repository 的 saveAll 方法
        repository.saveAll(productList);
    }

    @Override
    public ProductsDoc getById(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new RuntimeException("商品不存在"));
    }

    @Override
    public void deleteById(Long id) {
        repository.deleteById(id);
    }

    @Override
    public void delete(ProductsDoc doc) {
        repository.delete(doc);
    }

    /*
     * @Description: Description：从ES查询课程
     * 1.把dto中的查询条件，转换成ES的查询：NativeSearchQueryBuilder
     * 2.调用repository执行查询，得到Page
     * 3.把ES的Page 转换成 PageList
     */
    @Override
    public PageList<ProductsDoc> searchProducts(ProductsQueryDto dto) {
        //把dto中的查询条件，转换成ES的查询：NativeSearchQueryBuilder
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        //排序
        setSortAndPaging(dto, queryBuilder);

        //设置查询条件
        setQueryParam(dto, queryBuilder);

        //代码块说明：名字高亮
        setHighlight(queryBuilder);

        //设置聚合
        setAggr(queryBuilder);

        //执行查询
        AggregatedPage<ProductsDoc> page = template.queryForPage(queryBuilder.build(), ProductsDoc.class, highlightResultMapper);

        //处理聚合结果
        Map<String, List<AggrTermsBucket>> aggrMap = getAggrResult(page);

        //把ES的Page 转换成 PageList
        return new AggrPageList<ProductsDoc>(page.getTotalElements(),page.getContent(),aggrMap);
    }

    private Map<String, List<AggrTermsBucket>> getAggrResult(AggregatedPage<ProductsDoc> page) {
        //用来封装聚合结果
        Map<String,List<AggrTermsBucket>> aggrMap = new HashMap<>();

        //遍历聚合结果
        Aggregations aggregations = page.getAggregations();

        Map<String, Aggregation> stringAggregationMap = aggregations.asMap();

        Set<Map.Entry<String, Aggregation>> entries = stringAggregationMap.entrySet();

        entries.forEach(e->{
            //集合的名字
            String key = e.getKey();
            //集合的值的处理
            ParsedStringTerms value = (ParsedStringTerms)e.getValue();
            List<? extends Terms.Bucket> buckets = value.getBuckets();

            //使用lomda 把  List<StringTerms.Bucket>  转成  List<AggrTermsVo>
            List<AggrTermsBucket> aggrTermsVos = buckets.stream().map(bucket -> {
                return new AggrTermsBucket(bucket.getKeyAsString(), bucket.getDocCount());
            }).collect(Collectors.toList());

            aggrMap.put(key, aggrTermsVos);
        });
        return aggrMap;
    }

    //设置聚合
    private void setAggr(NativeSearchQueryBuilder queryBuilder) {
        TermsAggregationBuilder gradeNameAgg = AggregationBuilders
                .terms("gradeNameAgg") //聚合名
                .field("productsTypeId")    //按照课程分类聚合
                .order(BucketOrder.count(false))    //按照count排序，倒排
                .size(10);//取前10条

//        TermsAggregationBuilder chargeNameAgg = AggregationBuilders
//                .terms("chargeNameAgg") //聚合名
//                .field("chargeName")    //按照机构名聚合
//                .order(BucketOrder.count(false))    //按照count排序，倒排
//                .size(10);//取前10条
//        TermsAggregationBuilder courseTypeNameAgg = AggregationBuilders
//                .terms("courseTypeNameAgg") //聚合名
//                .field("courseTypeName")    //按照机构名聚合
//                .order(BucketOrder.count(false))    //按照count排序，倒排
//                .size(10);//取前10条

//        queryBuilder.addAggregation(gradeNameAgg).addAggregation(chargeNameAgg).addAggregation(courseTypeNameAgg);
        queryBuilder.addAggregation(gradeNameAgg);
    }

    //代码块说明：名字高亮
    private void setHighlight(NativeSearchQueryBuilder queryBuilder) {
        HighlightBuilder.Field  highlightField = new HighlightBuilder.Field("name")
                .preTags("<span style='color:red'>")
                .postTags("</span>");

        queryBuilder.withHighlightFields(highlightField);
    }

    //设置查询条件
    private void setQueryParam(ProductsQueryDto dto, NativeSearchQueryBuilder queryBuilder) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //must :商品名，关键字查询
        if(StringUtils.hasLength(dto.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("name", dto.getKeyword()));
            //boolQuery.must(QueryBuilders.multiMatchQuery(dto.getKeyword(),"name","tenantName"));
        }
        //课程类型
        if(dto.getProductsTypeId() != null){
            boolQuery.filter(QueryBuilders.termQuery("productsTypeId", dto.getProductsTypeId()));
        }
        //等级名
//        if(StringUtils.hasLength(dto.getGradeName())){
//            boolQuery.filter(QueryBuilders.termQuery("gradeName", dto.getGradeName()));
//        }
        //最小价格
        if(null != dto.getPriceMin()){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin()));
        }
        //最大价格
        if(null != dto.getPriceMax()){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }

        queryBuilder.withQuery(boolQuery);
    }

    //排序
    private void setSortAndPaging(ProductsQueryDto dto, NativeSearchQueryBuilder queryBuilder) {
        if(StringUtils.hasLength(dto.getSortField())){

            //默认新品
            String fieldName = null;

            switch (dto.getSortField().toLowerCase()){
                case "xl":fieldName = "saleCount";break;//销量
                case "xp":fieldName = "createDate";break;//上架时间
                case "pl":fieldName = "commentCount";break;//评论数
                case "jg":fieldName = "price";break;//商品原价
                case "rq":fieldName = "viewCount";break;//浏览量
                default: fieldName = "createDate";//上架时间
            }

            SortOrder sortOrder = SortOrder.DESC;

            if(StringUtils.hasLength(dto.getSortType()) && dto.getSortType().toLowerCase().equals("asc")){
                sortOrder = SortOrder.ASC;
            }

            //排序
            queryBuilder.withSort(SortBuilders.fieldSort(fieldName).order(sortOrder));
        }
        //分页
        queryBuilder.withPageable(PageRequest.of(dto.getPage() - 1, dto.getRows()));
    }
}
